# 测试向数据库中插入一条记录
import time
import sys
import mysql.connector
import datetime

# 定义数据库配置
config = {
    'user': 'talon',
    'password': 'xhwykzv',
    'host': 'localhost',
    'database': 'talon'
}


class Database:
    def __init__(self, config):
        try:
            self.cnx = mysql.connector.connect(**config)
            print("数据库连接成功\r\n")
        except mysql.connector.Error as err:
            print(f'连接失败：{err}')

    def execute(self, query, data=None):
        cursor = self.cnx.cursor()
        try:
            cursor.execute(query, data)
            rowcount = cursor.rowcount
            self.cnx.commit()
            cursor.close()
            return rowcount
        except mysql.connector.Error as err:
            self.cnx.rollback()
            cursor.close()
            print(f'执行失败：{err}')
            return None

    def close(self):
        self.cnx.close()
        print('连接已关闭。')


# 连接数据库
db = Database(config)

# 定义插入语句和数据
sql = "INSERT INTO sensor (time, temperature, humidity, mode) VALUES (%s, %s, %s, %s)"
nowtime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
data = (nowtime, 25.5, 70.0, 0)
# 执行插入操作
result = db.execute(sql, data)
if result is not None:
    print(f'成功插入{result}条记录。')
